<template>
  <div class="appEdit">
    <n-card title="">
      <template #header>
        <n-space>
          <div><n-avatar :size="68" :src="app.appOutputDto.icon" /> </div>
          <div>
            <div style="font-size: 24px; margin-left: 20px">{{ app.name }}</div>
            <div style="font-size: 14px; color: rgb(85, 85, 85, 0.7); margin-left: 20px"
              >适用于: {{ app.platform }}</div
            >
            <div style="font-size: 14px; color: rgb(85, 85, 85, 0.7); margin-left: 20px">
              <n-ellipsis :line-clamp="1"> 描述: {{ app.appOutputDto.description }} </n-ellipsis>
            </div>
          </div>
        </n-space>
      </template>
      <template #header-extra>
        <n-space>
          <n-button
            strong
            secondary
            round
            type="primary"
            @click="clickDownload(app.appOutputDto.shortCode)"
          >
            <template #icon>
              <n-icon>
                <EyeOutlined />
              </n-icon>
            </template>
            预览</n-button
          >
          <n-popconfirm
            @positive-click="handlePositiveClick(app.appId)"
            @negative-click="handleNegativeClick"
          >
            <template #trigger>
              <n-button strong secondary round type="error">
                <template #icon>
                  <n-icon>
                    <RestOutlined />
                  </n-icon>
                </template>
                删除</n-button
              >
            </template>
            是否删除应用?
          </n-popconfirm>
        </n-space>
      </template>
      <n-space justify="space-between">
        <n-h6 prefix="bar" align-text type="primary">
          <n-text type="primary">BundleID</n-text>
          <div>{{ app.bundleId }}</div>
        </n-h6>
        <n-h6 prefix="bar" align-text type="primary">
          <n-text type="primary">短链接</n-text>
          <div>{{ app.appOutputDto.installPath }}</div>
        </n-h6>
        <n-h6 prefix="bar" align-text type="primary">
          <n-text type="primary">版本</n-text>
          <div>{{ app.version }}</div>
        </n-h6>
      </n-space>
    </n-card>
    <n-card style="margin-top: 20px">
      <BasicTable
        :title="tableTitle"
        :request="loadDataTable"
        :columns="columns"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      />
    </n-card>
    <div>
      <n-modal
        v-model:show="formModal"
        @positive-click="submitCallback"
        @negative-click="cancelCallback"
        @close="cancelCallback"
        preset="dialog"
        title="应用编辑"
        positive-text="确认"
        negative-text="取消"
      >
        <n-card
          :bordered="false"
          :style="{
            maxWidth: '340px',
          }"
        >
          <n-form
            :label-width="80"
            :model="formApp"
            label-placement="left"
            :style="{
              maxWidth: '340px',
            }"
          >
            <n-form-item label="应用名称" path="name">
              <n-input :disabled="true" v-model:value="formApp.name" />
            </n-form-item>
            <n-form-item label="BundleID" path="bundleId">
              <n-input :disabled="true" v-model:value="formApp.bundleId" />
            </n-form-item>
            <n-form-item label="应用版本" path="version">
              <n-input :disabled="true" v-model:value="formApp.version" />
            </n-form-item>
            <n-form-item label="预览链接" path="previewUrl">
              <n-input :disabled="true" v-model:value="formApp.previewUrl" />
            </n-form-item>
            <n-form-item label="更新时间" path="displayTime">
              <n-input :disabled="true" v-model:value="formApp.displayTime" />
            </n-form-item>
            <n-form-item label="文件大小" path="displaySize">
              <n-input :disabled="true" v-model:value="formApp.displaySize" />
            </n-form-item>
            <n-form-item label="下载次数" path="extra">
              <n-input :disabled="true" v-model:value="formApp.extra" />
            </n-form-item>
            <n-form-item label="应用描述" path="description">
              <n-input type="textarea" v-model:value="formApp.description" />
            </n-form-item>
          </n-form>
        </n-card>
      </n-modal>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { EyeOutlined, RestOutlined } from '@vicons/antd';
  import { BasicTable, TableAction } from '@/components/Table';
  import { columns } from './components/columns';
  import { useMessage } from 'naive-ui';
  import { useRouter, useRoute } from 'vue-router';
  import { h, ref, reactive, onMounted } from 'vue';
  import { getPackages, deleteApp, deletePackage, updateApp } from '@/api/apps/app';
  const router = useRouter();
  const route = useRoute();
  const message = useMessage();
  const actionRef = ref();
  const tableTitle = ref('版本信息');
  const formModal = ref(false);
  const params = ref({
    pageSize: 5,
    name: 'xiaoMa',
  });
  const formApp = ref({
    id: 0,
    name: '',
    version: '',
    platform: '',
    previewUrl: '',
    bundleId: '',
    displayTime: '',
    displaySize: '',
    extra: '',
    description: '',
  });
  const app = ref({
    appId: 0,
    icon: '',
    name: '',
    version: '',
    platform: '',
    bundleId: '',
    previewUrl: '',
    appOutputDto: {
      icon: '',
      description: '',
      installPath: '',
      shortCode: '',
    },
  });
  const shortCode = ref();
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              if (app.value.id == record.id) {
                return false;
              } else {
                return true;
              }
            },
          },
          {
            label: '下载',
            align: 'center',
            onClick: handleDown.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });
  const loadDataTable = async (res) => {
    if (route.query.code) {
      shortCode.value = route.query.code;
    }
    const formParams = {
      shortCode: shortCode.value,
    };
    const result = await getPackages({ ...formParams, ...params.value, ...res });
    console.log({ result });
    const data = result.data;
    app.value = data.records[0];
    return {
      list: data.records,
      page: data.pageNum,
      pageSize: data.pageSize,
      pageCount: data.total,
    };
  };

  const onCheckedRow = (rowKeys) => {
    console.log(rowKeys);
  };
  const handleEdit = (record: Recordable) => {
    formModal.value = true;
    formApp.value.id = record.id;
    formApp.value.name = record.name;
    formApp.value.version = record.version;
    formApp.value.platform = record.platform;
    formApp.value.previewUrl = record.appOutputDto.installPath;
    formApp.value.bundleId = record.bundleId;
    formApp.value.displayTime = record.displayTime;
    formApp.value.displaySize = record.displaySize;
    formApp.value.extra = record.extra;
    formApp.value.description = record.appOutputDto.description;
  };
  const submitCallback = () => {
    const data = new FormData();
    data.append('id', formApp.value.id);
    data.append('description', formApp.value.description);
    updateApp(data)
      .then((res) => {
        if (res.data) {
          message.success('更新成功');
          actionRef.value.reload();
          formModal.value = false;
        }
      })
      .catch((err) => {
        message.error('更新失败');
        console.log({ err });
      });
  };
  const cancelCallback = () => {
    formModal.value = false;
  };
  const handleDown = (record: Recordable) => {
    window.location.href = record.downloadUrl;
    actionRef.value.reload();
  };

  const handleDelete = (record: Recordable) => {
    deletePackage(record.id)
      .then((res) => {
        if (res.data) {
          message.info('删除成功');
          actionRef.value.reload();
        }
      })
      .catch((err) => {
        message.info('删除失败');
        console.log(err);
      });
  };
  const clickDownload = (code) => {
    const { href } = router.resolve({
      path: '/preview',
      query: { code: code },
    });
    window.open(href, '_blank');
  };
  const handlePositiveClick = (appId) => {
    deleteApp(appId)
      .then((res) => {
        if (res.data) {
          message.info('删除成功');
          router.push({
            path: '/list/apps',
          });
        }
      })
      .catch((err) => {
        message.info('删除失败');
        console.log(err);
      });
  };
  const handleNegativeClick = () => {};
  onMounted(async () => {});
</script>
<style lang="less" scoped>
  .n-layout-sider {
    width: 70px;
  }
</style>
